import cv2
import numpy as np
from yolov5.predict import predict
from determine import determine
from recognition import extract_text


# 将图像转换为灰度图像
def convert_to_gray(image):
    return cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)


# 调整图像大小，调整后的图像尺寸默认为(1084, 669)
def resize_image(image, size=(1084, 669)):
    return cv2.resize(image, size)


def preprocess_image(img, points, size=(1084, 669)):
    top, bottom, left, right = points
    img = img[top:bottom, left:right]  # 初步裁剪

    # 透视变换校正
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    edged = cv2.Canny(gray, 50, 150)  # 边缘检测
    contours, _ = cv2.findContours(edged, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    contours = sorted(contours, key=cv2.contourArea, reverse=True)[:5]  # 取最大轮廓

    screenCnt = None
    for c in contours:
        peri = cv2.arcLength(c, True)
        approx = cv2.approxPolyDP(c, 0.02 * peri, True)
        if len(approx) == 4:  # 找到四边形
            screenCnt = approx.reshape(4, 2)
            break

    if screenCnt is not None:
        img = four_point_transform(img, screenCnt)  # 校正图像

    # 调整为固定尺寸
    transformed_image = cv2.resize(img, size)
    gray_image = cv2.cvtColor(transformed_image, cv2.COLOR_BGR2GRAY)
    return gray_image, transformed_image


# 预处理
def preprocess_image2(img, points, size=(1084, 669)):
    top = points[0]
    bottom = points[1]
    left = points[2]
    right = points[3]

    img = img[top:bottom, left:right]

    transformed_image = resize_image(img, size)  # 固定shape

    gray_image = convert_to_gray(transformed_image)  # 转换为灰度图像

    return gray_image, transformed_image


def order_points(pts):
    rect = np.zeros((4, 2), dtype="float32")
    s = pts.sum(axis=1)
    rect[0] = pts[np.argmin(s)]  # 左上角
    rect[2] = pts[np.argmax(s)]  # 右下角
    diff = np.diff(pts, axis=1)
    rect[1] = pts[np.argmin(diff)]  # 右上角
    rect[3] = pts[np.argmax(diff)]  # 左下角
    return rect


def four_point_transform(image, pts):
    rect = order_points(pts)
    (tl, tr, br, bl) = rect
    # 计算新图像的宽度和高度
    widthA = np.sqrt(((br[0] - bl[0]) ** 2) + ((br[1] - bl[1]) ** 2))
    widthB = np.sqrt(((tr[0] - tl[0]) ** 2) + ((tr[1] - tl[1]) ** 2))
    maxWidth = max(int(widthA), int(widthB))
    heightA = np.sqrt(((tr[0] - br[0]) ** 2) + ((tr[1] - br[1]) ** 2))
    heightB = np.sqrt(((tl[0] - bl[0]) ** 2) + ((tl[1] - bl[1]) ** 2))
    maxHeight = max(int(heightA), int(heightB))
    # 定义目标坐标
    dst = np.array([
        [0, 0],
        [maxWidth - 1, 0],
        [maxWidth - 1, maxHeight - 1],
        [0, maxHeight - 1]], dtype="float32")
    # 执行透视变换
    M = cv2.getPerspectiveTransform(rect, dst)
    warped = cv2.warpPerspective(image, M, (maxWidth, maxHeight))
    return warped

# if __name__ == "__main__":
#     img = cv2.imread("hello.jpg")
#     top, bottom, left, right = predict("hello.jpg")
#     points = [top, bottom, left, right]
#     g, t = preprocess_image(img, points)
#     determine(g)
#     text = extract_text()
#     print(text)